# _*_ coding:utf-8 _*_
# @File  : time_recport.py
# @Time  : 2021-09-29  10:23
# @Author: zizle

# 定期报告
import datetime

from fastapi import APIRouter, Query, Path, Body
from db import FAConnection
from db import utils as dbutils
from status import r_status
from utils.constant import VARIETY_ZH
from configs import WEB_HOST
time_report_api = APIRouter()


# 获取各类报告数据,参数为类型
@time_report_api.get('/', summary='获取各类报告数据,参数为类型')
async def get_time_reports(page: int = Query(..., ge=1), page_size: int = Query(..., ge=30, le=200),
                           category: int = Query(..., ge=1)):
    start_record, offset = (page - 1) * page_size, page_size
    sql = 'SELECT SQL_CALC_FOUND_ROWS id,create_time,file_date,variety_en,title,file_type,filepath,reading,is_active ' \
          'FROM research_file WHERE file_type=%s ' \
          'ORDER BY file_date DESC LIMIT %s,%s;'
    db = FAConnection(conn_name='admin查询报告')
    records = db.query(sql, param=[category, start_record, offset], keep_conn=True)
    total_obj = db.query('SELECT FOUND_ROWS() AS total;', fetchone=True)[0]
    total_count = total_obj['total'] if total_obj else 1  # 当前总数
    for item in records:
        item['create_time'] = datetime.datetime.fromtimestamp(item['create_time']).strftime('%Y-%m-%d')
        item['file_date'] = datetime.datetime.fromtimestamp(item['file_date']).strftime('%Y-%m-%d')
        item['variety_name'] = ','.join([VARIETY_ZH.get(v, v) for v in item['variety_en'].split(';')])
        item['filepath'] = WEB_HOST + item['filepath']
    return {'code': r_status.SUCCESS, 'message': '获取报告数据成功!', 'page': page, 'page_size': page_size,
            'data': records, 'total_count': total_count}


# 修改一条报告信息
@time_report_api.put('/{report_id}/', summary='设置报告信息')
async def modify_report(report_id: int = Path(..., ge=1), report_item: dict = Body(...)):
    columns = ['is_active']
    report_item = dbutils.exclude_columns(report_item, columns)
    m_sql = dbutils.create_sql(report_item)
    sql = 'UPDATE research_file SET ' + m_sql + 'WHERE id=%(id)s LIMIT 1;'
    report_item['id'] = report_id
    db = FAConnection(conn_name='admin修改报告')
    _, success = db.execute(sql, param=report_item)
    if success:
        return {'code': r_status.SUCCESS, 'message': '修改成功!'}
    return {'code': r_status.UNKNOWN_ERROR, 'message': '修改失败了,服务器错误!'}

